﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Security.Cryptography;
using System.Runtime.InteropServices;
using appLibrary;
using Npgsql;
using NpgsqlTypes;
using System.Threading;



namespace appDeskSistAcademico
{
    public partial class FrmLogin : Form
    {

        /// <summary>
        /// Key for the crypto provider
        /// </summary>
        private static readonly byte[] _key = { 0xA1, 0xF1, 0xA6, 0xBB, 0xA2, 0x5A, 0x37, 0x6F, 0x81, 0x2E, 0x17, 0x41, 0x72, 0x2C, 0x43, 0x27 };
        /// <summary>
        /// Initialization vector for the crypto provider
        /// </summary>
        private static readonly byte[] _initVector = { 0xE1, 0xF1, 0xA6, 0xBB, 0xA9, 0x5B, 0x31, 0x2F, 0x81, 0x2E, 0x17, 0x4C, 0xA2, 0x81, 0x53, 0x61 };

        public FrmLogin()
        {
            InitializeComponent();
            //this.time
            //Thread th = new Thread(new ThreadStart();
           
            //System.Windows.Forms.Timer timer = new System.Windows.Forms.Timer();


            FrmSplash frmSplash = new FrmSplash();
            frmSplash.Show();
            frmSplash.Update();
            Thread.Sleep(3000);
            frmSplash.Hide();

            //th.Start();
            //Thread.Sleep(3000);
            //th.Abort();
            //Thread.Sleep(1000);             
            
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            
            //Close();
            System.Windows.Forms.Application.Exit();
           
                    
         
        }

        private void btnLogin_Click(object sender, EventArgs e)
        {
            //txtLogin.Text = "ADMIN";
            //txtPwd.Text = "1";
            int idRole = 0;
            int idUser = 0;
            if (login(ref idRole, ref idUser))
            {
                FrmMain frmMain = new FrmMain();
                frmMain.user = txtLogin.Text;
                frmMain.idUser = idUser;
                frmMain.idRole = idRole;
                frmMain.Show();
                //FrmMDIMain frmMDIMain = new FrmMDIMain();
                //frmMDIMain.Show();
                this.Hide();
            }
           
           

        }

        private void lblChangedPWD_Click(object sender, EventArgs e)
        {
            int idRole = 0;
             int idUser = 0;
            if (login(ref idRole,ref idUser))
            {
                //FrmRoleMant frmRoleMant = new FrmRoleMant();
                //frmRoleMant.user = txtLogin.Text;
                //frmRoleMant.idUser = idUser;
                //frmRoleMant.idRole = idRole;
                //frmRoleMant.typeAcces = 2;
                //frmRoleMant.Tag = "1";
                //frmRoleMant.ShowDialog();

                //frmRoleMant.codigo=txt

           
            }
        }

        private void FrmLogin_Load(object sender, EventArgs e)
        {
            //appLibrary.Splash splash = new Splash("splash1.jpg");
            txtLogin.CharacterCasing = CharacterCasing.Upper;
            
            
        }

        private void groupBox1_Enter(object sender, EventArgs e)
        {
           // Windows wind = new Windows();
            
        }

        private void timer1_Tick(object sender, EventArgs e)
        {

        }

        private void txtPwd_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                btnLogin_Click(sender, e);
            }
        }

        private void txtLogin_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
                txtPwd.Focus();
                
        }



        private bool login(ref int idRole, ref int idUser  )
        {
            try
            {
                // txtLogin.Text = "ADMIN";
                // txtPwd.Text = "admin";
                string strUser = txtLogin.Text;
                ViewQueries viewQueries = new ViewQueries();

                DataSet dts = viewQueries.getSPQueries("public.sp_queries_by_user", null, txtLogin.Text, txtPwd.Text);

                if (dts != null && dts.Tables != null && dts.Tables[0].Rows.Count > 0 && dts.Tables[0].Rows[0]["state"].ToString().Trim().Equals("1"))
                {
                    
                    idUser=Convert.ToInt32(dts.Tables[0].Rows[0][0].ToString());
                    idRole = Convert.ToInt32(dts.Tables[0].Rows[0]["id_rol"].ToString());
                  


                }
                else
                {
                    if (dts != null && dts.Tables != null && dts.Tables[0].Rows.Count > 0 && dts.Tables[0].Rows[0]["state"].ToString().Trim().Equals("0"))

                        MessageBox.Show(this, "El usuario se encuentra bloqueado.\nFavor de comunicarse con el Administrador del Sistema.", "Sistema Integrado Minero", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    else
                        MessageBox.Show(this, "El Usuario o Contraseña no es válido.", "Sistema Integrado Minero", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);

                    txtLogin.Clear();
                    txtPwd.Clear();
                    txtLogin.Focus();
                    return false;
                }
                return true;
            }
            catch (Exception ex)
            {
                Log.eLog("Unkwown", "Se obtuvo errores al intenta loguearse:" + ex.ToString());
                MessageBox.Show(this, "Se generaron errores al intentar accesar al sistema:" + ex.Message);
                return false;
            }
        }

        private void lblChangedPWD_MouseMove(object sender, MouseEventArgs e)
        {
            lblChangedPWD.BackColor = Color.YellowGreen;
        }

        private void groupBox1_MouseHover(object sender, EventArgs e)
        {
            //lblChangedPWD.BackColor = Color.White;
        }

        private void btnLogin_MouseMove(object sender, MouseEventArgs e)
        {
           // lblChangedPWD.BackColor = Color.White;
        }

        private void btnCancel_MouseMove(object sender, MouseEventArgs e)
        {
            //lblChangedPWD.BackColor = Color.White;
        }

        private void lblChangedPWD_MouseLeave(object sender, EventArgs e)
        {
            lblChangedPWD.BackColor = Color.White;
        }

        private void lblChangedPWD_MouseDown(object sender, MouseEventArgs e)
        {
            lblChangedPWD.BorderStyle = BorderStyle.Fixed3D;
        }

        private void lblChangedPWD_MouseUp(object sender, MouseEventArgs e)
        {
            lblChangedPWD.BorderStyle = BorderStyle.None;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            //List<double> arr = new List<double>();
            //arr.Add(2.3);
            //arr.Add(1.34);
           
            //double desvStd = DesviacionStandard(arr);
            //MessageBox.Show(desvStd.ToString());
            if (Util.IsValidEmailAddress("miguel.rivera@nyrstar.com"))
                MessageBox.Show(this, "es valido");
            else
                MessageBox.Show(this, "No es valido");
        }


        double DesviacionStandard(List<double> listaDatos)
        {
            double desvStd = 0;
            double N = 0, prom = 0, suma = 0, NrestadoUno = 0, sumapotencias = 0;
            N = listaDatos.Count;
            NrestadoUno = N - 1;
            foreach (double dato in listaDatos)
            {
                suma += dato;
            }
            prom = suma / N;
            foreach (double dato in listaDatos)
            {
                sumapotencias += Math.Pow((dato - prom), 2);
            }
            desvStd = Math.Sqrt((1 * sumapotencias) / NrestadoUno);
            return desvStd;
        }

        
    }
}
